package com.xinxuan.usercenter.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.xinxuan.usercenter.auth.CheckLogin;
import com.xinxuan.usercenter.domain.BonusEventLog;
import com.xinxuan.usercenter.domain.User;
import com.xinxuan.usercenter.dto.JwtTokenRespDTO;
import com.xinxuan.usercenter.dto.LoginRespDTO;
import com.xinxuan.usercenter.dto.UserLoginDTO;
import com.xinxuan.usercenter.dto.UserRespDTO;
import com.xinxuan.usercenter.service.UserService;
import com.xinxuan.usercenter.util.JwtOperator;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;

@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private JwtOperator jwtOperator;

    @GetMapping("/me")
    @CheckLogin
    public User me(@RequestHeader("X-Token") String token) {
        return userService.me(token);
    }

    @GetMapping("/{id}")
    @CheckLogin
    public User findById(@PathVariable Integer id) {
        log.info("被調用了");
        return userService.findById(id);
    }

    @PostMapping("/login")
    public LoginRespDTO login(@RequestBody UserLoginDTO loginDTO) throws WxErrorException {
        // 微信小程序校验是否登录结果
        WxMaJscode2SessionResult result = wxMaService.getUserService().getSessionInfo(loginDTO.getCode());
        // 微信的openid 唯一标识
        String openid = result.getOpenid();
        // 看用户是否注册 没有就注册插入
        // 如果注册了，就直接颁发token
        User user = userService.login(loginDTO, openid);
        Map<String, Object> userInfo = new HashMap<>(3);
        userInfo.put("id", user.getId());
        userInfo.put("wxNickName", user.getWxNickname());
        userInfo.put("role", user.getRoles());
        String token = jwtOperator.generateToken(userInfo);
        log.info("用户{}登录成功，生成的token={}，有效期到：{}", loginDTO.getWxNickname(), token,
            jwtOperator.getExpirationDateFromToken(token));

        LoginRespDTO build = LoginRespDTO.builder()
            .user(UserRespDTO.builder().id(user.getId()).avatarUrl(user.getAvatarUrl()).bonus(user.getBonus())
                .wxNickname(user.getWxNickname()).build())
            .token(JwtTokenRespDTO.builder().expirationTime(jwtOperator.getExpirationDateFromToken(token).getTime())
                .token(token).build())
            .build();
        return build;
    }

    @GetMapping("/gen-token")
    public String genToken() {
        Map<String, Object> userInfo = new HashMap<>(3);
        userInfo.put("id", 1);
        userInfo.put("wxNickName", "狮子王");
        userInfo.put("role", "user");
        return jwtOperator.generateToken(userInfo);
    }

    @GetMapping("/bonus-logs")
    @CheckLogin
    public List<BonusEventLog> bonusLogs(@RequestHeader("X-Token") String token) {
        return userService.bonusLogs(token);
    }

    @GetMapping("/sign")
    @CheckLogin
    public User sign(@RequestHeader("X-Token") String token) {
        return userService.sign(token);
    }
}
